package com.tanhua.server.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.dubbo.server.api.QuanZiApi;
import com.tanhua.dubbo.server.api.VideoApi;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.server.pojo.User;
import com.tanhua.server.pojo.UserInfo;
import com.tanhua.server.utils.UserThreadLocal;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.PicUploadResult;
import com.tanhua.server.vo.VideoVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

@Service
public class VideoService {

    @Reference(version = "1.0.0")
    private VideoApi videoApi;

    @Autowired
    private PicUploadService picUploadService;

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private FdfsWebServer fdfsWebServer;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference(version = "1.0.0")
    private QuanZiApi quanZiApi;

    public String saveVideo(MultipartFile picFile, MultipartFile videoFile) {

        User user = UserThreadLocal.get();

        Video video = new Video();
        video.setUserId(user.getId());
        video.setSeeType(1);

        try {
            //上传封面图片至阿里云oss
            PicUploadResult uploadResult = picUploadService.upload(picFile);
            video.setPicUrl(uploadResult.getName());

            //上传视频至FastDFS:参数3为截图源文件的后缀名
            StorePath storePath = storageClient.uploadFile(videoFile.getInputStream(), videoFile.getSize(), StringUtils.substringAfter(videoFile.getOriginalFilename(), "."), null);
            video.setVideoUrl(fdfsWebServer.getWebServerUrl() + storePath.getFullPath());//拼接得到的路径可通过网页直接访问
            //fdfsWebServer.getWebServerUrl()获取配置文件中的访问路径前缀

            return videoApi.saveVideo(video);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public PageResult queryVideoList(Integer page, Integer pageSize) {

        User user = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);

        PageInfo<Video> pageInfo = null;

        //先从Redis进行命中，如果命中则返回推荐列表，如果未命中查询默认列表
        String redisValue = this.redisTemplate.opsForValue().get("QUANZI_VIDEO_RECOMMEND_" + user.getId());
        if (StringUtils.isNotEmpty(redisValue)) {
            String[] vids = StringUtils.split(redisValue, ',');
            int startIndex = (page - 1) * pageSize;
            if (startIndex < vids.length) {
                int endIndex = startIndex + pageSize - 1;
                if (endIndex >= vids.length) {
                    endIndex = vids.length - 1;
                }

                List<Long> vidList = new ArrayList<>();
                for (int i = startIndex; i <= endIndex; i++) {
                    vidList.add(Long.valueOf(vids[i]));
                }

                List<Video> videoList = this.videoApi.queryVideoListByPids(vidList);
                if (!CollectionUtils.isEmpty(videoList)) {
                    pageInfo = new PageInfo<>();
                    pageInfo.setRecords(videoList);
                }
            }
        }

        if (null == pageInfo) {
            pageInfo = this.videoApi.queryVideoList(page, pageSize);
        }

        List<Video> records = pageInfo.getRecords();

        List<VideoVo> videoVoList = new ArrayList();

        HashSet<Long> userIds = new HashSet();

        for (Video record : records) {

            userIds.add(record.getUserId());

            VideoVo videoVo = new VideoVo();

            videoVo.setId(record.getId().toHexString());
            videoVo.setUserId(record.getUserId());//视频的发布用户
            videoVo.setCover(record.getPicUrl());//视频封面图片
            videoVo.setVideoUrl(record.getVideoUrl());//小视频url
            videoVo.setSignature("我就是我~"); //TODO 签名

            //是否关注(1是 0否)
            String followUserKey = "VIDEO_FOLLOW_USER_" + user.getId() + "_" + videoVo.getUserId();
            videoVo.setHasFocus(redisTemplate.hasKey(followUserKey) ? 1 : 0);

            //是否点赞:1点赞 0未点赞
            String likeCommentKey = "QUANZI_COMMENT_LIKE_USER_" + user.getId() + "_" + videoVo.getId();
            //判断是否点赞,如果redis中存在likeCommentKey的key,则值一定为1,否则该key就不存在,直接被delete掉了,因此此处可以通过hasKey来做条件判断
            videoVo.setHasLiked(redisTemplate.hasKey(likeCommentKey) ? 1 : 0);

            //点赞数
            String likeCommentCountKey = "QUANZI_COMMENT_LIKE_" + videoVo.getId(); //publishId
            String likeCount = redisTemplate.opsForValue().get(likeCommentCountKey);
            //点赞总数,在redis中是通过自增自减进行操作的,即除非该key过期或第一次被访问,否则会一直存在
            if (StringUtils.isNotEmpty(likeCount)) { //当字符串为null或""时,返回false
                videoVo.setLikeCount(Integer.valueOf(likeCount));
            } else {
                videoVo.setLikeCount(0);
            }

            //评论数
            Long commentCount = quanZiApi.queryCommentCount(videoVo.getId(), 2);
            videoVo.setCommentCount(commentCount == null ? 0 : commentCount.intValue());

            videoVoList.add(videoVo);
        }

        QueryWrapper<UserInfo> wrapper = new QueryWrapper();
        wrapper.in("user_id", userIds);
        List<UserInfo> userInfos = this.userInfoService.queryUserInfoList(wrapper);
        for (VideoVo videoVo : videoVoList) {
            for (UserInfo userInfo : userInfos) {
                if (videoVo.getUserId().longValue() == userInfo.getUserId().longValue()) {
                    videoVo.setNickname(userInfo.getNickName());
                    videoVo.setAvatar(userInfo.getLogo());
                    break;
                }
            }
        }

        pageResult.setItems(videoVoList);
        return pageResult;
    }

    //关注用户
    public Boolean followUser(Long userId) {
        User user = UserThreadLocal.get();
        this.videoApi.followUser(user.getId(), userId);

        //记录已关注
        String followUserKey = "VIDEO_FOLLOW_USER_" + user.getId() + "_" + userId;
        this.redisTemplate.opsForValue().set(followUserKey, "1");

        return true;
    }

    //取消关注
    public Boolean disFollowUser(Long userId) {
        User user = UserThreadLocal.get();
        this.videoApi.disFollowUser(user.getId(), userId);

        String followUserKey = "VIDEO_FOLLOW_USER_" + user.getId() + "_" + userId;
        this.redisTemplate.delete(followUserKey);

        return true;
    }
}
